package com.softWang.common.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.softWang.common.dataPermission.db.DataPermissionRuleHandler;
import com.softWang.common.dataPermission.rule.DataPermissionRule;
import com.softWang.common.dataPermission.rule.DataPermissionRuleFactory;
import com.softWang.common.dataPermission.rule.DataPermissionRuleFactoryImpl;
import com.softWang.common.mybatis.util.MyBatisUtils;
import com.softWang.common.tenent.db.TenantDatabaseInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;

@Configuration
public class MybatisPlusConfig {

    @Bean
    public DataPermissionRuleFactory dataPermissionRuleFactory(List<DataPermissionRule> rules) {
        return new DataPermissionRuleFactoryImpl(rules);
    }
    @Bean
    @Primary
    public MybatisPlusInterceptor mybatisPlusInterceptor(DataPermissionRuleFactory ruleFactory) {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 多租户插件
        TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor(new TenantDatabaseInterceptor());
        // 添加到 interceptor 中
        // 需要加在首个，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        MyBatisUtils.addInterceptor(mybatisPlusInterceptor, tenantInterceptor, 0);

        // 数据权限插件
        DataPermissionRuleHandler handler = new DataPermissionRuleHandler(ruleFactory);
        DataPermissionInterceptor inner = new DataPermissionInterceptor(handler);
        // 添加到 interceptor 中
        // 需要加在首个，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        MyBatisUtils.addInterceptor(mybatisPlusInterceptor, inner, 0);
        // 分页插件
        //mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}
